package com.shitu.base.rn;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.iqiyi.baselib.BuildConfig;
import com.shitu.base.net.API;
import com.shitu.base.net.model.User;
import com.shitu.base.net.model.result.ImgResulte;
import com.shitu.base.net.service.CommonService;
import com.shitu.base.rn.model.ToastMsg;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.config.ISListConfig;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class BaseRNActivity extends Activity implements DefaultHardwareBackBtnHandler {
    private static int REQUEST_LIST_CODE = 0x002;

    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;
    private ProgressDialog progress;

    private Promise promise;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.jsbundle")
                .setJSMainModulePath("index.android")
                .addPackage(new MainReactPackage())
                .addPackage(new EventPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        // The string here (e.g. "MyReactNativeApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, "Soulemo", getIntent().getBundleExtra("info"));

        setContentView(mReactRootView);
    }


    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostPause(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostResume(this, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostDestroy(this);
        }
        if (mReactRootView != null) {
            mReactRootView.unmountReactApplication();
        }

        hideLoading();
    }

    @Override
    public void onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    public void handleEvent(String uniqueID, final ReadableMap params, final Promise promise) {
        Log.i("rn", "id = " + uniqueID + ", params = " + params.toString());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                handle(params.getString("action"), params);
            }
        });
        this.promise = promise;
    }

    public void handle(String action, ReadableMap params) {
        if (!action.equals("takePhoto")) {
            this.promise = null;
        }
        if (action.equals("saveLoginData")) {
            Log.i("abc", params.getString("params"));
            User user = JSON.parseObject(params.getString("params"), User.class);
            token = user.token;
        } else if (action.equals("showLoading")) {
            showLoading();
        } else if (action.equals("hideLoading")) {
            hideLoading();
        } else if (action.equals("showToast")) {
            toast(JSON.parseObject(params.getString("params"), ToastMsg.class).toastMsg);
        } else if (action.equals("popViewController")) {
            finish();
        } else if (action.equals("takePhoto")) {
            ISListConfig config = new ISListConfig.Builder()
                    // 是否多选, 默认true
                    .multiSelect(false)
                    // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                    .rememberSelected(false)
                    // “确定”按钮背景色
                    .btnBgColor(Color.GRAY)
                    // “确定”按钮文字颜色
                    .btnTextColor(Color.parseColor("#52CBC6"))
                    // 使用沉浸式状态栏
                    .statusBarColor(Color.parseColor("#52CBC6"))
                    // 返回图标ResId
                    .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material)
                    // 标题
                    .title("图片")
                    // 标题文字颜色
                    .titleColor(Color.WHITE)
                    // TitleBar背景色
                    .titleBgColor(Color.parseColor("#52CBC6"))
                    // 裁剪大小。needCrop为true的时候配置
                    .cropSize(1, 1, 200, 200)
                    .needCrop(true)
                    // 第一个是否显示相机，默认true
                    .needCamera(true)
                    // 最大选择图片数量，默认9
                    .maxNum(1)
                    .build();

            // 跳转到图片选择器
            ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");
            if (!pathList.isEmpty()) {
                updloadImg(pathList.get(0));
            }
        }
    }


    private void showLoading() {
        progress = new ProgressDialog(this);
        progress.show();
    }

    private void hideLoading() {
        if (progress != null && progress.isShowing()) {
            progress.dismiss();
        }
    }

    private void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void updloadImg(String url) {
        compressPicture(url);
        API.send(CommonService.updateImg(url, token), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("tag", "fail img");
                promise = null;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                final ImgResulte re = JSON.parseObject(str, ImgResulte.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (promise != null) {
                            promise.resolve(re.url);
                            promise = null;
                        }
                    }
                });
            }
        });
    }

    private void compressPicture(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (bitmap.getHeight() > 300 || bitmap.getWidth() > 300) {
            float scaleW = bitmap.getWidth() * 1.0f / 300;
            float scaleH = bitmap.getHeight() * 1.0f / 300;
            float scale = Math.max(scaleH, scaleW);
            Bitmap compressedPic = Bitmap.createScaledBitmap(bitmap,
                    (int) (bitmap.getWidth() / scale),
                    (int) (bitmap.getHeight() / scale), true);
            File file = new File(path);
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                compressedPic.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}